// pages/users.js
"use client";

import React, { useState, useEffect } from "react";
import { Table, Button, Modal, Form, Input, Row, message,Popconfirm } from "antd";

const Users = () => {
  const [users, setUsers] = useState([]);
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const columns = [
    {
      title: "id",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "用户",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "密码",
      dataIndex: "password",
      key: "password",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },

    {
      title: "操作",
      key: "actions",
      render: (_: any, record: any) => (
        <span>
          <Button
            type="primary"
            className="mr-2"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>

          <Popconfirm

            description="确定删除吗?"
            onConfirm={() => handleDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Button type="primary" danger >
              删除
            </Button>
          </Popconfirm>
        </span>
      ),
    },
  ];

  const handleEdit = (record: any) => {
    // Implement edit functionality
    console.log("Edit user:", record);
  };
 
  const handleDelete =async (record: any) => {
    //删除
    // Implement delete functionality
     let res = await fetch(`/api/admin/users?id=${record.id}`, {
      method: "Delete",
      headers: {
        "Content-Type": "application/json",
      },
    });
        res = await res.json();
    if (res.success) {
      message.success("删除成功");
      getUserList("");
    } else {
      message.error("删除失败");
    }
    console.log("Delete user:", record);
  };

  const handleSearch = (values: { username: any }) => {
    // Implement search functionality based on username
    getUserList(values.username);

    console.log("Search:", values.username);
  };

  const showModal = () => {
    form.resetFields();
    setVisible(true);
  };

  const handleOk = async () => {
    // Implement add user functionality
    console.log("Add user:", form.getFieldsValue());
    let res = await fetch("/api/admin/users", {
      method: "POST",
      body: JSON.stringify(form.getFieldsValue()),
      headers: {
        "Content-Type": "application/json",
      },
    });
    res = await res.json();
    if (res.success) {
      message.success("添加成功");
      getUserList("");
    } else {
      message.error("添加失败");
    }
    console.log("res", res);
    setVisible(false);
  };

  const handleCancel = () => {
    setVisible(false);
  };
  const getUserList = async (username: string) => {
    const res = await fetch(`/api/admin/users?username=${username}`);
    const data = await res.json();
    console.log("data", data);
    setUsers(data.data);
  };
  useEffect(() => {
    // Fetch users data from your API or any data source
    // Update the 'users' state with the fetched data
    // Example:
    getUserList("");
    // const mockUsers = [
    //   { key: '1', username: 'user1' },
    //   { key: '2', username: 'user2' },
    // ];
    // setUsers(mockUsers);
  }, []);

  return (
    <div>
      <Button type="primary" className="m-3" onClick={showModal}>
        添加用户
      </Button>

      <Row gutter={16} className="m-3">
        {/* 查询用户 */}
        <Form layout="inline" onFinish={handleSearch}>
          <Form.Item name="username" label="用户名">
            <Input placeholder="Username" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>
      </Row>
      <Table dataSource={users} columns={columns} />

      <Modal
        title="Add User"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="username"
            label="Username"
            rules={[{ required: true, message: "请输入用户名称" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Users;
